import React, { useReducer, useRef, useState } from 'react'
import './index.less'

import { useForceUpdate } from '../../hooks/useForceUpdate'
const Tab = ({ children, onChange }) => {
	const activeIndex = useRef(null)
	const tabList = []
	let renderChildren = null
	const forceUpdate = useForceUpdate()
	React.Children.forEach(children, (item) => {
		if (React.isValidElement(item) && item.type.displayName === 'tabItem') {
			const { props } = item
			const { name, label } = props
			const tabItem = {
				name,
				label,
				active: name === activeIndex.current,
				component: item,
			}
			if (name === activeIndex.current) renderChildren = item
			tabList.push(tabItem)
		}
	})

	// 第一次渲染
	if (!renderChildren && tabList.length > 0) {
		const firstChildren = tabList[0]
		renderChildren = firstChildren.component
		activeIndex.current = firstChildren.component.props.name
		firstChildren.active = true
	}

	// 切换 tab
	const changeTab = (name) => {
		activeIndex.current = name
		forceUpdate()
		onChange && onChange(name)
	}

	return (
		<div>
			<div className="tab">
				{tabList.map((tab) => (
					<div
						className="tab-item"
						key={tab.name}
						onClick={() => changeTab(tab.name)}
					>
						<div className={tab.active ? 'label active' : 'label'}>
							{tab.label}
						</div>
					</div>
				))}
			</div>
			<div>{renderChildren}</div>
		</div>
	)
}

Tab.displayName = 'tab'

export default Tab
